import os
import json
import logging
from pathlib import Path
import time
from utils.data_utils import DataUtils

class Config:
    """应用配置管理类"""

    def __init__(self):
        # 项目根目录
        self.BASE_DIR = Path(__file__).resolve().parent

        # 资源目录
        self.RESOURCES_DIR = self.BASE_DIR / "resources"

        # 加载配置文件
        self.config_file = self.RESOURCES_DIR / "config.json"
        self.config = self.load_config()

        # 日志配置
        self.LOG_DIR = self.BASE_DIR / "logs"
        self.setup_logging()

        self.data_utils = DataUtils()
        # 创建必要目录
        self.LOG_DIR.mkdir(exist_ok=True)
        (self.RESOURCES_DIR / "icons").mkdir(exist_ok=True)

    def load_config(self):
        """加载配置文件"""
        default_config = {
            "serial": {
                "port": "",
                "baudrate": 9600,
                "bytesize": 8,
                "parity": "none",
                "stopbits": 1,
                "timeout": 0.1
            },
            "modbus": {
                "device_address": 1,
                "frame_interval": 3.5,
                "response_timeout": 20,
                "poll_interval": 1.0
            },
            "gui": {
                "window_size": "1200x800",
                "theme": "clam"
            },
            "registers": [
                {"address": "0x0000", "name": "温度传感器1", "unit": "°C", "type": "int16"},
                {"address": "0x0001", "name": "温度传感器2", "unit": "°C", "type": "int16"},
                {"address": "0x0002", "name": "压力传感器", "unit": "kPa", "type": "int16"},
                {"address": "0x0003", "name": "湿度传感器", "unit": "%RH", "type": "int16"},
                {"address": "0x0004", "name": "设备状态", "unit": "", "type": "uint16"},
                {"address": "0x0005", "name": "运行时间", "unit": "小时", "type": "uint32"},
                {"address": "0x0006", "name": "设定值", "unit": "", "type": "int16"}
            ]
        }

        if self.config_file.exists():
            try:
                with open(self.config_file, 'r') as f:
                    return json.load(f)
            except json.JSONDecodeError:
                logging.error("配置文件损坏，使用默认配置")
                return default_config
        return default_config

    def save_config(self):
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w') as f:
                json.dump(self.config, f, indent=4)
            logging.info("配置保存成功")
            return True
        except Exception as e:
            logging.error(f"保存配置失败: {str(e)}")
            return False

    def setup_logging(self):
        """配置日志系统"""
        log_file = self.LOG_DIR / f"modbus_monitor_{time.strftime('%Y%m%d')}.log"
        if not os.path.exists(self.LOG_DIR):
            os.mkdir(self.LOG_DIR)
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(filename= log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )

    def get_serial_config(self):
        """获取串口配置"""
        return self.config.get("serial", {})

    def get_modbus_config(self):
        """获取Modbus配置"""
        return self.config.get("modbus", {})

    def get_gui_config(self):
        """获取GUI配置"""
        return self.config.get("gui", {})

    def get_register_config(self):
        """获取寄存器配置"""
        return self.config.get("registers", [])

    def update_serial_config(self, key, value):
        """更新串口配置"""
        if "serial" not in self.config:
            self.config["serial"] = {}
        self.config["serial"][key] = value

    def update_modbus_config(self, key, value):
        """更新Modbus配置"""
        if "modbus" not in self.config:
            self.config["modbus"] = {}
        self.config["modbus"][key] = value

    def update_register_config(self, registers):
        """更新寄存器配置"""
        self.config["registers"] = registers